import axios from 'axios';
import router from "./router.ts";
import useUserStore from "../stores/system/user.ts";

const instance = axios.create({
    baseURL: import.meta.env.VITE_GLOB_API_BASE_URL,
    timeout: 5000,
});

instance.interceptors.request.use(
    function(config){
        const userStore = useUserStore();
        if(userStore.token) {
            config.headers.set("Authorization", userStore.token);
        }
        return config;
    },
);

instance.interceptors.response.use(
    function (response) {
        //判断返回码
        if (response.data.code >= 400) {
            return Promise.reject(response);
        }
        //返回请求结果
        return response;
    },
    function (error) {
        //判断授权过期
        if(error.response.status == 401) {
            router.push("/login");
            return Promise.reject(error);
        }
        //响应调用错误
        return Promise.reject(error);
    }
);

export default instance;